package com.cg.bank.web.util;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ExceptionHandler;
import org.apache.struts.config.ExceptionConfig;

/**
 * bank异常处理器
 * 
 * @author chunges
 * @date 2018年9月1日 上午9:10:22
 * @version V1.0
 */

public class BankExceptionHandler extends ExceptionHandler {

	@Override
	public ActionForward execute(Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm formInstance,
			HttpServletRequest request, HttpServletResponse response) throws ServletException {
		if (!(ex instanceof AppException)) {
			return super.execute(ex, ae, mapping, formInstance, request, response);
		}
		ex.printStackTrace();
		AppException appException = (AppException) ex;
		ActionForward forward = null;
		ActionMessage error = null;
		String property = appException.getErrorKey();

		int len = property.lastIndexOf(".");
		if (len == -1) {
			if (ae.getPath() != null) {
				forward = new ActionForward(ae.getPath());
			} else {
				forward = mapping.getInputForward();
			}
		} else {
			String path = property.substring(len + 1);
			forward = new ActionForward(mapping.findForward(path).getPath());
		}

		error = new ActionMessage(property, appException.getParameters());
		logException(ex);
		request.setAttribute(Globals.EXCEPTION_KEY, ex);
		// 保存错误信息
		storeException(request, property, error, forward, mapping.getScope());
		return forward;
	}

}